package main

import (
    "net/http"
    "os/exec"
    "io/ioutil"
)

func acme(w http.ResponseWriter, result ResponseData){

    str_cmd  := "/usr/bin/acme.sh"
    str_opt1 := "--issue"
    str_opt2 := "-d" 
    str_opt3 := domain
    str_opt4 := "--webroot"
    str_opt5 := g_config.Webroot
    str_opt6 := "--force"
    str_opt7 := "--debug"
    
    mainlog.Println(str_cmd, str_opt1, str_opt2, str_opt3, str_opt4, str_opt5, str_opt6, str_opt7)
    /*
        /usr/bin/acme.sh --issue -d 4.jyydcdn.com --webroot /data/acme/ --force --debug
    */
    cmd := exec.Command(str_cmd, str_opt1, str_opt2, str_opt3, str_opt4, str_opt5, str_opt6, str_opt7)
    
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        mainlog.Println("StdoutPipe:", err)
    }

    // 保证关闭输出流
    defer stdout.Close()

    // 运行命令
    if err := cmd.Start(); err != nil {
        mainlog.Println("Start:", err)
        postCaToServer("", "", 3)
        return
    }

    // 读取输出结果
    opBytes, err := ioutil.ReadAll(stdout)
    if err != nil {
        mainlog.Println("ReadAll:", err)
    }

    mainlog.Println(string(opBytes))

    strBase := "/root/.acme.sh/"
    strBase += domain
    strBase += "/"

    key := strBase + domain + ".key"
    cer := strBase + "fullchain.cer"

    datFullchainCer, err1 := ioutil.ReadFile(cer)
    datDomainKey, err2 := ioutil.ReadFile(key)

    if err1 != nil || err2 != nil{
        mainlog.Println("ReadFile error:")
        mainlog.Println("证书生成失败")
        postCaToServer("", "", 3)
        return
    }else{
        mainlog.Println("证书生成成功")
        postCaToServer(string(datFullchainCer), string(datDomainKey), 1)
    }
}